﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.Common;
using Midapex.SmartOrm.Tools.Wizard.Properties;

namespace Midapex.SmartOrm.Tools.Wizard
{
    public partial class SqlServerConnForm : Form
    {
        public SqlServerConnForm()
        {
            InitializeComponent();
        }

        private void refreshButton_Click(object sender, EventArgs e)
        {
            try
            {
                System.Data.Sql.SqlDataSourceEnumerator instance = System.Data.Sql.SqlDataSourceEnumerator.Instance;
                System.Data.DataTable dataTable = instance.GetDataSources();

                List<string> servers = new List<string>();

                foreach (System.Data.DataRow row in dataTable.Rows)
                {
                    string serverName = row["ServerName"].ToString();
                    string instanceName = row["InstanceName"].ToString();
                    if(string.IsNullOrEmpty(instanceName))
                    {
                        servers.Add(serverName);
                    }
                    else
                    {
                        servers.Add(serverName + "\\" + instanceName);
                    }
                }

                serverComboBox.Items.Clear();
                //string[] servers = SqlLocator.GetServers();
                if (servers == null)
                {
                    return;
                }
                foreach (string server in servers)
                {
                    serverComboBox.Items.Add(server);
                }

                if (servers.Count != 0)
                {
                    serverComboBox.SelectedIndex = 0;
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(this, ex.Message, Resources.Warning, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void winAuthRadioButton_CheckedChanged(object sender, EventArgs e)
        {
            if (this.winAuthRadioButton.Checked)
            {
                userTextBox.Enabled = false;
                pwdTextBox.Enabled = false;
            }
            else
            {
                userTextBox.Enabled = true;
                pwdTextBox.Enabled = true;
            }
        }

        public string CreateConnString(string dataBase)
        {
            string connString = "";
            
            if (winAuthRadioButton.Checked)
            {
                connString = string.Format("Server={0};Integrated Security=SSPI", serverComboBox.Text);
            }
            else if (sqlAuthRadioButton.Checked)
            {
                connString = string.Format("Server={0};User={1};Password={2}", 
                    serverComboBox.Text, userTextBox.Text, pwdTextBox.Text);
            }

            if(!string.IsNullOrEmpty(dataBase))
            {
                connString += ";Database=" + dataBase;
            }

            return connString;
        }
        
        private void testConnButton_Click(object sender, EventArgs e)
        {
            try
            {
                OrmSessionsFactory.SetConfig(DataSourceType.SqlServer,CreateConnString(null));

                OrmSession session = OrmSessionsFactory.CreateSession();
                using (DbConnection conn = session.CreateDbConnection() )
                {
                    conn.Open();
                    dbComboBox.Items.Clear();

                    string sqlCmd = "SELECT NAME FROM SYSDATABASES";
                    DbCommand cmd = session.CreateDbCommand(sqlCmd);
                    cmd.Connection = conn;

                    IDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        dbComboBox.Items.Add(reader.GetString(0));
                    }

                    if (dbComboBox.Items.Count != 0)
                    {
                        dbComboBox.SelectedIndex = 0;
                    }
                }
                btnCreateNewDB.Enabled = true;
                MessageBox.Show(this, Resources.ConnDataSourceSuccess, Resources.Information, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                btnCreateNewDB.Enabled = false;

                MessageBox.Show(this, ex.Message, Resources.Warning, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void SqlServerConnForm_Load(object sender, EventArgs e)
        {

        }

        internal string GetConnString()
        {
            if(dbComboBox.SelectedItem!=null)
            {
                return CreateConnString(dbComboBox.SelectedItem.ToString());
            }
            else
            {
                return null;
            }
        }

        private void NewDB_Click(object sender, EventArgs e)
        {
            try
            {
                OrmSessionsFactory.SetConfig(DataSourceType.SqlServer,
                    CreateConnString("master"));

                OrmSession session = OrmSessionsFactory.CreateSession();
                string newDbName = dbComboBox.Text;
                string sqlCmd = "create database " + newDbName;
                session.ExecuteNonQuery(sqlCmd);

                dbComboBox.Items.Clear();

                sqlCmd = "SELECT NAME FROM SYSDATABASES";
                using(DbConnection conn = session.CreateDbConnection())
                {
                    conn.Open();
                    DbCommand cmd = session.CreateDbCommand(sqlCmd);
                    cmd.Connection = conn;

                    IDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        dbComboBox.Items.Add(reader.GetString(0));
                    }

                    dbComboBox.Text = newDbName;
                    reader.Close();
                    conn.Close();
                }
                MessageBox.Show(this, Resources.CreateDbSuccess,
                Resources.Information, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, Resources.Warning, 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void buttonOk_Click(object sender, EventArgs e)
        {
            if(string.IsNullOrEmpty(GetConnString()))
            {
                MessageBox.Show("Please input SQL Server information");
                return;
            }

            DialogResult = DialogResult.OK;
        }
    }
}